#include "osapi.h"
#include "user_interface.h"
#include "spi_flash.h"

#include "app_flash.h"

#define ALIG_ADDRESS_N(p, align)    ((p + align - 1) & ~(align - 1))


void ICACHE_FLASH_ATTR app_flash_write(void * data, uint32 flash_addr, uint32 length)
{
    SpiFlashOpResult ret;
    int i;
    uint8 * da = data;
    ret = spi_flash_erase_sector(flash_addr / 4096);
    if (ret)
    {
        os_printf("x>flash erase 0x%x failed\n",flash_addr / 4096);
        return;
    }
    ret = spi_flash_write(flash_addr, (uint32 *)data, ALIG_ADDRESS_N(length, 4));
    os_printf("=>save 0x%x(len=%d) in 0x%x is %d\n", data, length, flash_addr, ret);
    for (i = 0;i < ALIG_ADDRESS_N(length, 4); i++)
    {
        os_printf("0x%x ",da[i]);
    }
    os_printf("\n");
}

void ICACHE_FLASH_ATTR app_flash_read(void * data, uint32 flash_addr, uint32 length)
{
    SpiFlashOpResult ret;
    int i;
    uint8 * da = data;
    ret = spi_flash_read(flash_addr, (uint32 *)data, ALIG_ADDRESS_N(length, 4));
    os_printf("=>read 0x%x(len=%d) in 0x%x is %d\n", data, length, flash_addr, ret);
    for (i = 0;i < ALIG_ADDRESS_N(length, 4); i++)
    {
        os_printf("0x%x ",da[i]);
    }
    os_printf("\n");
}

